if (document.querySelector('.user-logining')) {
  document.querySelector('.user-logining').addEventListener('click', () => {
    let user = document.querySelector('.user')
    if (!user.classList.contains('user-active')) {
      user.classList.add('user-active')
    } else {
      user.classList.remove('user-active')
    }
  })

}

//用户点击退出
document.querySelector('.user-out').addEventListener('click', () => {
  document.querySelector('.modal-out').style.display = 'flex'
})
document.querySelector('.modal-out').addEventListener('click', function (e) {
  if (e.target == this) {
    this.style.display = 'none'
  }
})
document.querySelector('.modal-out form button').addEventListener('click', () => {
  document.querySelector('.modal-out').style.display = 'none'
})

function article() {
  let line = document.querySelector('.search-top .line')
  let board = document.querySelector('.board')
  let centerArticle = document.querySelector('.center-article')
  let liebiao = document.querySelector('.search-top .liebiao')
  let sort = document.querySelector('.search .sort')
  line.style.left = '100px'
  liebiao.classList.remove('spanActive')
  document.querySelector('.search-top .shuxian').classList.add('spanActive')
  centerArticle.style.display = 'flex'
  sort.style.display = 'flex'
  board.style.display = 'none'
  document.querySelector('.search-form-input').placeholder = '输入要搜索的文章';
  document.cookie = "wenzhang=true; path=/"
  document.querySelector('.search-form-type').value = 'wz'
  wlhref('search')
}

// //文章点击事件
// document.querySelector('.search-top .shuxian').addEventListener('click', () => {
//   window.location.href = '../view/index.php?sort=hot'
//   article()
// })

//添加文章跳转页面
document.querySelector('.right-add').addEventListener('click', () => {
  window.location.href = 'http://127.0.0.1:8080/speakUp/view/addArtIndex.php'
  console.log(123)
})



//文章的详细请求
document.querySelector('.center-article').addEventListener('click', (e) => {
  if (e.target.closest('.center-article-item')) {
    const item = e.target.closest('.center-article-item')
    const newUrl = window.location.pathname + `?aid=${item.dataset.art}`
    history.pushState({ aid: item.dataset.art }, '', newUrl)
    $.ajax({
      url: 'userIndex.php',
      type: 'GET',
      data: { aid: item.dataset.art },
      success: function (response) {
        // 解析响应并更新页面
        const parser = new DOMParser()
        const doc = parser.parseFromString(response, 'text/html')
        const newContent = doc.querySelector('.article').innerHTML
        document.querySelector('.article').innerHTML = newContent
        initArt()
      },
      error: function (xhr, status, error) {
        console.error('请求失败:', status, error)
      }
    })
  }

})
// 文章展示样式函数
function initArt() {
  const params = new URLSearchParams(window.location.search)
  const aid = params.get('aid')
  if (aid != null && aid != '') {
    document.cookie = "aid=yes;path=/"
    document.querySelector('.article').style.right = '0vw'
  } else {
    document.cookie = "aid=;path=/"
    document.querySelector('.article').style.right = '-150vw'
  }
}
initArt()


document.querySelector('.article').addEventListener('click', function (e) {
  if (e.target == this) {
    document.cookie = "aid=;path=/"
    history.pushState({}, '', window.location.pathname);
    this.style.right = '-150vw'
  }
})
function getCookie(key) {
  return document.cookie.split(';').map(item => item.trim()).find(item => item.startsWith(key + '='))?.split('=')[1];
}


document.addEventListener('click', (e) => {
  //修改文章
  if (e.target.closest('.changeArt')) {
    let aid = new URLSearchParams(window.location.search).get('aid')
    console.log(aid)
    window.location.href = `./changeArt.php?aid=${aid}`
  }
  //点赞功能
  if (e.target.closest('.icon-dianzan') || e.target.closest('.icon-dianzan_kuai')) {
    const dzBtn = e.target.closest('.icon-dianzan, .icon-dianzan_kuai');
    let uname = getCookie('user')
    let aid = new URLSearchParams(window.location.search).get('aid')
    $.ajax({
      url: "../control/like",
      type: 'post',
      data: { uname, aid },
      success: (res) => {
        if (res.code === 200) {
          dzBtn.classList.toggle('icon-dianzan', !res.liked)
          dzBtn.classList.toggle('icon-dianzan_kuai', res.liked)
          const likeCountEl = dzBtn.parentNode.querySelector('span')
          console.log(likeCountEl)
          if (likeCountEl) {
            const currentCount = parseInt(likeCountEl.textContent)
            likeCountEl.textContent = res.liked ? currentCount + 1 : currentCount - 1
          }
        } else {
          errMsg(res.msg)
        }
      },
      error: (err) => {
        errMsg(err)
      }
    })
  }

  //评论按钮
  if (e.target.closest('.sendbtn')) {
    let sendBtn = e.target.closest('.sendbtn')
    let text = sendBtn.parentNode.querySelector('textarea')
    let zshu = sendBtn.parentNode.querySelector('.textNum .wordCount')
    let aid = new URLSearchParams(window.location.search).get('aid')
    let uname = getCookie('user')
    console.log(uname)
    if (text.value.trim().length <= 0) {
      errMsg('请输入评论的内容')
      return
    }

    $.ajax({
      url: '../control/userCom.php',
      type: 'post',
      data: { aid, uname, content: text.value.trim() },
      success: (res) => {

        if (res.code == 200) {
          let nr = document.querySelector('.user-parent-comment').innerHTML
          document.querySelector('.user-parent-comment').innerHTML = `
                 <li class="user-reply" data-cid="${res.cid}" data-who="${res.whoid}">
        <div class="user-reply-main">
          <div class="user-reply-top">
            <span>${uname}</span>
            <span>刚刚</span>
          </div>
          <p>${text.value.trim()}</p>
          <div class="user-reply-footer">

            <span class="replySpan">回复</span>
            <span class='delCom'>删除</span>
          </div>
          <div class="user-reply-footer-com">
            <textarea cols="180" rows="5" maxlength="150" placeholder="发一条友善的评论吧~"></textarea>
            <button class="repBtn"><i class="iconfont icon-fasong"></i>回复</button>
            <div class="textNum"><span class="wordCount">0</span>/<span>150</span></div>
          </div>
        </div>
        <ul class="user-reply-son"></ul>
        </li>
                `+ nr
          document.querySelector('.box-reply span:nth-child(1) span').innerHTML++
          zshu.textContent = 0
          text.value = ''
        } else {
          errMsg(res.msg)
        }
      }, error: (err) => {
        console.log(err)
        errMsg(err.message)
      }
    })
  }

  // 回复按钮展示
  if (e.target.closest(".replySpan")) {
    let repSpan = e.target.closest(".replySpan")
    if (!repSpan) {
      return
    }

    let main = repSpan.parentNode.parentNode.querySelector('.user-reply-footer-com')
    if (main.classList.contains('ractive')) {
      main.classList.remove('ractive')
    } else {
      document.querySelectorAll('.ractive').forEach(item => {
        item.classList.remove('ractive')
      })
      main.classList.add('ractive')
    }


  }

  //回复评论按钮
  if (e.target.closest(".repBtn")) {
    let repBtn = e.target.closest(".repBtn")
    if (!repBtn) {
      return
    }
    // console.log(repBtn.parentNode.parentNode.parentNode)
    let li = repBtn.parentNode.parentNode.parentNode
    let text = repBtn.parentNode.querySelector('textarea')
    let zshu = repBtn.parentNode.querySelector('.textNum .wordCount')
    if (text.value.trim().length <= 0) return errMsg('回复信息不能为空')

    let cid = li.dataset.cid
    let content = text.value.trim()
    let who = li.dataset.who
    let aid = new URLSearchParams(window.location.search).get('aid')
    let uname = getCookie('user')
    $.ajax({
      url: "../control/userRep.php",
      type: 'post',
      data: { cid, content, who, aid, uname },
      success: (res) => {
        if (res.code == 200) {
          const replyList = li.querySelector('.user-reply-son')
          replyList.innerHTML += `
              <li class="son-reply" data-cid="${cid}" data-who="${res.uid}" data-rid ="${res.rid}">
                <div class="son-reply-main">
                  <div class="son-reply-top">
                    <span>${getCookie('user')} <span>:回复${res.uname}</span></span>
                    <span>刚刚</span>
                  </div>
                  <p>${content}</p>
                  <div class="son-reply-footer">
          
                    <span>回复</span>
                    <span class='delRep'>删除</span>
                  </div>
                  <div class="son-reply-footer-com">
                    <textarea cols="180" rows="5" maxlength="150" placeholder="发一条友善的评论吧~"></textarea>
                    <button class="sonRepBtn"><i class="iconfont icon-fasong"></i>回复</button>
                    <div class="textNum"><span class="wordCount">0</span>/<span>150</span></div>
                  </div>
                </div>
              </li>
            `
          repBtn.parentNode.parentNode.querySelector('.user-reply-footer').innerHTML += `<span class="shou"><i class="iconfont icon-xiangxia1"></i></span>`
          document.querySelector('.box-reply span:nth-child(1) span').innerHTML++
          text.value = ''
          zshu.textContent = 0
          document.querySelectorAll('.ractive').forEach(item => {
            item.classList.remove('ractive')
          })
          if (!replyList.classList.contains('hactive')) {
            replyList.classList.add('hactive')
          }
        } else {
          errMsg(res.msg)
        }
      },
      error: (err) => {
        console.log(err)
      }
    })

  }

  //展开回复按钮
  if (e.target.closest(".shou")) {
    let span = e.target.closest(".shou")
    if (!span) return
    let ul = span.parentNode.parentNode.parentNode.querySelector('.user-reply-son')
    if (ul.classList.contains('hactive')) {
      ul.classList.remove('hactive')
    } else {
      ul.classList.add('hactive')
    }
  }

  //展开回复回复按钮
  if (e.target.closest(".son-reply-footer span:nth-child(1)")) {
    let sonRep = e.target.closest(".son-reply-footer")
    if (!sonRep) return
    let li = sonRep.parentNode.parentNode
    let repBox = li.querySelector('.son-reply-footer-com')
    if (repBox.classList.contains('ractive')) {
      repBox.classList.remove('ractive')
    } else {
      document.querySelectorAll('.ractive').forEach(item => {
        item.classList.remove('ractive')
      })
      repBox.classList.add('ractive')
    }
  }
  //回复回复按钮
  if (e.target.closest('.sonRepBtn')) {
    let sonRepBtn = e.target.closest('.sonRepBtn')
    if (!sonRepBtn) return
    console.log(sonRepBtn)
    let li = sonRepBtn.parentNode.parentNode.parentNode
    let text = sonRepBtn.parentNode.querySelector('textarea')
    let zshu = sonRepBtn.parentNode.querySelector('.textNum .wordCount')
    if (text.value.trim().length <= 0) return errMsg('回复消息不能为空')

    let cid = li.dataset.cid
    console.log(cid)
    let content = text.value.trim()
    let who = li.dataset.who
    let aid = new URLSearchParams(window.location.search).get('aid')
    let uname = getCookie('user')

    $.ajax({
      url: '../control/userRep.php',
      type: 'post',
      data: { cid, content, who, aid, uname },
      success: (res) => {
        if (res.code == 200) {
          let ul = li.parentNode
          ul.innerHTML += `
              <li class="son-reply" data-cid="${cid}" data-who="${res.uid}" data-rid ="${res.rid}">
                <div class="son-reply-main">
                  <div class="son-reply-top">
                    <span>${getCookie('user')} <span>:回复${res.uname}</span></span>
                    <span>刚刚</span>
                  </div>
                  <p>${content}</p>
                  <div class="son-reply-footer">
                    <span>回复</span>
                    <span class='delRep'>删除</span>
                  </div>
                  <div class="son-reply-footer-com">
                    <textarea cols="180" rows="5" maxlength="150" placeholder="发一条友善的评论吧~"></textarea>
                    <button class="sonRepBtn"><i class="iconfont icon-fasong"></i>回复</button>
                    <div class="textNum"><span class="wordCount">0</span>/<span>150</span></div>
                  </div>
                </div>
              </li>
            `;
          document.querySelector('.box-reply span:nth-child(1) span').innerHTML++
          text.value = ''
          zshu.textContent = 0
          document.querySelectorAll('.ractive').forEach(item => {
            item.classList.remove('ractive')
          })
          if (!ul.classList.contains('hactive')) {
            ul.classList.add('hactive')
          }
        } else {
          errMsg(res.msg)
        }
      },
      error: (err) => {
        console.log(err)
      }
    })
  }
})



document.querySelector('.article').addEventListener('input', (e) => {
  let textareaC = e.target.closest('.box-reply-inp textarea')
  let textareaR = e.target.closest('.ractive textarea') || null

  if (textareaC) {
    document.querySelector('.wordCount').textContent = textareaC.value.trim().length
  }
  if (textareaR) {
    document.querySelector('.ractive .wordCount').textContent = textareaR.value.trim().length
  }
});


function errMsg(msg) {
  let dzErr = document.querySelector('.dzErr')
  dzErr.querySelector('span').textContent = msg
  dzErr.style.transform = 'translateY(0)'
  setTimeout(() => {
    dzErr.style.transform = 'translateY(-100px)'
  }, 3000)
}
function saveMsg(msg) {
  let saveMsg = document.querySelector('.saveMsg')
  saveMsg.querySelector('span').textContent = msg
  saveMsg.style.transform = 'translateY(0)'
  setTimeout(() => {
    saveMsg.style.transform = 'translateY(-100px)'
  }, 3000)
}
